package com.ocss.system.service.impl;

import java.time.LocalDate;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import com.ocss.system.domain.*;
import com.ocss.system.domain.vo.CourseStudentAchievementVo;
import com.ocss.system.domain.vo.StudentCourseAchievementVo;
import com.ocss.system.mapper.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ocss.system.service.IOcssAchievementService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 成绩管理Service业务层处理
 *
 * @author ligen
 * @date 2024-03-09
 */
@Service
public class OcssAchievementServiceImpl implements IOcssAchievementService {
    @Autowired
    private OcssAchievementMapper ocssAchievementMapper;

    @Resource
    private IOcssCourseSelectionServiceImpl utils;

    @Resource
    private OcssCourseMapper ocssCourseMapper;

    @Resource
    private OcssElectiveCoursesMapper electiveCoursesMapper;

    @Resource
    private OcssStudentMapper studentMapper;

    @Resource
    private OcssAchievementMapper achievementMapper;

    @Resource
    private OcssProfessionMapper professionMapper;

    @Resource
    private OcssSemesterMapper semesterMapper;

    @Resource
    private OcssTeacherMapper teacherMapper;

    /**
     * 查询成绩管理
     *
     * @param id 成绩管理主键
     * @return 成绩管理
     */
    @Override
    public OcssAchievement selectOcssAchievementById(Long id) {
        return ocssAchievementMapper.selectOcssAchievementById(id);
    }

    /**
     * 查询成绩管理列表
     *
     * @param ocssAchievement 成绩管理
     * @return 成绩管理
     */
    @Override
    public List<OcssAchievement> selectOcssAchievementList(OcssAchievement ocssAchievement) {
        return ocssAchievementMapper.selectOcssAchievementList(ocssAchievement);
    }

    /**
     * 新增成绩管理
     *
     * @param ocssAchievement 成绩录入
     * @return 结果
     */
    @Override
    @Transactional
    public int insertOcssAchievement(OcssAchievement ocssAchievement) {

        OcssAchievement a = new OcssAchievement();
        a.setCourseId(ocssAchievement.getCourseId());
        a.setStudentId(ocssAchievement.getStudentId());
        // 先判断该课程和学生的成绩信息是否存在数据库中
        List<OcssAchievement> ocssAchievements = ocssAchievementMapper.selectOcssAchievementList(a);

        if (!ocssAchievements.isEmpty()) {
            // 存在的话执行修改操作
            OcssAchievement achievement = ocssAchievements.get(0);
            achievement.setAchievement(ocssAchievement.getAchievement());

            return ocssAchievementMapper.updateOcssAchievement(achievement);
        }
        // 不存在执行添加操作
        return ocssAchievementMapper.insertOcssAchievement(ocssAchievement);
    }

    /**
     * 修改成绩管理
     *
     * @param ocssAchievement 成绩管理
     * @return 结果
     */
    @Override
    public int updateOcssAchievement(OcssAchievement ocssAchievement) {
        return ocssAchievementMapper.updateOcssAchievement(ocssAchievement);
    }

    /**
     * 批量删除成绩管理
     *
     * @param ids 需要删除的成绩管理主键
     * @return 结果
     */
    @Override
    public int deleteOcssAchievementByIds(Long[] ids) {
        return ocssAchievementMapper.deleteOcssAchievementByIds(ids);
    }

    /**
     * 删除成绩管理信息
     *
     * @param id 成绩管理主键
     * @return 结果
     */
    @Override
    public int deleteOcssAchievementById(Long id) {
        return ocssAchievementMapper.deleteOcssAchievementById(id);
    }

    // 教师所教授课程列表
    @Override
    public List<OcssCourse> selectTeacherCourseList(OcssCourse ocssCourse) {

        Long pid = utils.getStudentId();

        // 从课程表中查询到所有该教师教授的选课时间已结束或状态为3的所有课程
        ocssCourse.setTeacherId(pid);

        List<OcssCourse> ocssCourses = ocssCourseMapper.selectOcssCourseList(ocssCourse);

        // 过滤出今天的时间大于 courseEndTime 的所有课程数据
        List<OcssCourse> filteredCourses = ocssCourses.stream()
                .filter(course -> {
                    Date courseEndTime = course.getCourseEndTime();
                    LocalDate now = LocalDate.now();
                    LocalDate endDate = courseEndTime.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
                    return now.isAfter(endDate) || course.getStatus().equals("3");
                })
                .collect(Collectors.toList());

        return filteredCourses;
    }

    // 学生成绩列表
    @Override
    public List<StudentCourseAchievementVo> selectStudentCourseList(OcssCourse ocssCourse) {

        // 查询到学生自己所有 有成绩的课程 并显示成绩
        Long pid = utils.getStudentId();
        OcssAchievement ocssAchievement = new OcssAchievement();
        ocssAchievement.setStudentId(pid);
        List<OcssAchievement> ocssAchievements = ocssAchievementMapper.selectOcssAchievementList(ocssAchievement);

        if (!ocssAchievements.isEmpty()) {

            List<StudentCourseAchievementVo> collect = ocssAchievements.stream().map(oas -> {

                OcssCourse course = ocssCourseMapper.selectOcssCourseById(oas.getCourseId());

                StudentCourseAchievementVo cVo = new StudentCourseAchievementVo();
                cVo.setAchievement(oas.getAchievement());
                cVo.setCourseName(course.getCourseName());
                cVo.setClassLocation(course.getClassLocation());
                cVo.setCourseType(course.getCourseType());
                cVo.setCourseNumber(course.getCourseNumber());
                cVo.setCredit(course.getCredit());
                cVo.setClassTimer(course.getClassTimer());

                OcssProfession ocssProfession = professionMapper.selectOcssProfessionById(course.getProfessionId());
                cVo.setProfession(ocssProfession.getProfessionName());

                OcssSemester ocssSemester = semesterMapper.selectOcssSemesterById(course.getSemesterId());
                cVo.setSemester(ocssSemester.getSemesterName());

                OcssTeacher ocssTeacher = teacherMapper.selectOcssTeacherById(course.getTeacherId());
                cVo.setTeacherName(ocssTeacher.getName());


                return cVo;
            }).collect(Collectors.toList());

            return collect;
        }


        return new ArrayList<>();
    }


    // 课程列表中学生名单
    @Override
    public List<CourseStudentAchievementVo> selectCourseStudentList(OcssStudent student, Long courseId) {

        OcssElectiveCourses ocssElectiveCourses = new OcssElectiveCourses();
        ocssElectiveCourses.setCourseId(courseId);

        List<OcssElectiveCourses> electiveCoursesList = electiveCoursesMapper.selectOcssElectiveCoursesList(ocssElectiveCourses);

        if (!electiveCoursesList.isEmpty()) {

            Long[] sids = electiveCoursesList.stream()
                    .map(OcssElectiveCourses::getStudentId)
                    .toArray(Long[]::new);

            List<OcssStudent> s = studentMapper.selectOcssStudentByIds(sids);

            // 组装对象 返回给前端显示的字段
            List<CourseStudentAchievementVo> achievementList = s.stream()
                    .filter(stu -> {
                        String name = stu.getName();
                        String schoolNumber = stu.getSchoolNumber();
                        String studentName = student.getName();
                        String studentSchoolNumber = student.getSchoolNumber();

                        // 判断 studentName 是否为空
                        if (studentName == null) {
                            // 判断 studentSchoolNumber 是否为空，如果为空直接返回 true，表示过滤条件不生效
                            if (studentSchoolNumber == null) {
                                return true;
                            } else {
                                // 只根据 studentSchoolNumber 进行过滤
                                return studentSchoolNumber.equals(schoolNumber);
                            }
                        }

                        // 判断 studentSchoolNumber 是否为空
                        if (studentSchoolNumber == null) {
                            // 只根据 studentName 进行过滤
                            return name != null && name.contains(studentName);
                        }

                        // 根据 studentName 和 studentSchoolNumber 进行过滤
                        return name != null && name.contains(studentName) || studentSchoolNumber.equals(schoolNumber);
                    })
                    .map(stu -> {
                        CourseStudentAchievementVo vo = new CourseStudentAchievementVo();

                        // 如果有成绩 则将加入成绩
                        OcssAchievement ocssAchievement = new OcssAchievement();
                        ocssAchievement.setStudentId(stu.getId());
                        ocssAchievement.setCourseId(courseId);
                        List<OcssAchievement> ocssAchievements = achievementMapper.selectOcssAchievementList(ocssAchievement);
                        if (!ocssAchievements.isEmpty()) {
                            vo.setAchievement(ocssAchievements.get(0).getAchievement());
                        }

                        vo.setId(stu.getId());
                        vo.setAddress(stu.getAddress());
                        vo.setAge(stu.getAge());
                        vo.setName(stu.getName());
                        vo.setPhone(stu.getPhone());
                        vo.setNationality(stu.getNationality());
                        vo.setIdCard(stu.getIdCard());
                        vo.setSchoolNumber(stu.getSchoolNumber());
                        vo.setSex(stu.getSex());
                        vo.setNativePlace(stu.getNativePlace());
                        vo.setGrade(stu.getGrade());

                        return vo;
                    })
                    .collect(Collectors.toList());


            return achievementList;
        }


        return new ArrayList<>();

    }
}
